import time
from fastapi import HTTPException
from zoneinfo import ZoneInfo
import user_agents
from datetime import datetime
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
import os
import geoip2.database
from core.Config import settings

from core.Log import log_admin_event
# 获取 FastAPI 启动脚本的主目录路径

# 构建 GeoLite2-City.mmdb 文件的完整路径
geoip_db_path = os.path.join(settings.STATIC_DIR, 'data', 'GeoLite2-City.mmdb')
# 打开 GeoLite2 数据库
geoip_reader = geoip2.database.Reader(geoip_db_path)
class BaseMiddleware(BaseHTTPMiddleware):
  async def dispatch(self, request: Request, call_next):
        # 记录请求开始时间
        start_time = time.time()

        # 获取请求方法和 IP 地址
        method = request.method
        client_ip = request.client.host

        # 获取地理位置信息
        try:
            location_data = geoip_reader.city(client_ip)
            location = f"{location_data.city.name}, {location_data.country.name}" if location_data.city.name else location_data.country.name
        except Exception:
            location = "Unknown"
            
        # 获取用户代理信息
        user_agent_str = request.headers.get("user-agent")
        user_agent = user_agents.parse(user_agent_str)

        # 获取操作系统和浏览器类型
        os_info = user_agent.os.family
        browser_info = user_agent.browser.family

        # 处理请求，获取响应
        response = await call_next(request)

        # 记录请求结束时间和处理时间
        process_time = time.time() - start_time
        process_time_ms = process_time * 1000  # 转换为毫秒

        # 记录日志信息
        log_admin_event(
            f"Method: {method}, IP: {client_ip}, Location: {location}, "
            f"OS: {os_info}, Browser: {browser_info}, "
            f"Process Time: {process_time_ms:.2f} ms"
        )
        return response
